package com.neouton.crm.pm.service.impl;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.neouton.common.entity.ActivitiVO;
import com.neouton.common.util.*;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.approval.service.IApprovalService;
import com.neouton.crm.dictionary.entity.DictionaryLookupItemVO;
import com.neouton.crm.dictionary.service.IDictionaryService;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.pm.entity.PurchaseOrderVO;
import com.neouton.crm.pm.mapper.InternalPurchaseMapper;
import com.neouton.crm.pm.service.IInternalPurchaseService;
import com.neouton.crm.transpondEmail.service.TranspondEmailService;
import com.neouton.feginClient.FeginService;
import com.neouton.feginClient.WorkFlowFeginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * 采购相关Service
 * @Author libingkun
 * @Date 2022年11月30日
 * @Version 1.0
 *          初始化迁移
 */
@Service
public class InternalPurchaseServiceImpl implements IInternalPurchaseService {

    @Resource
    private WorkFlowFeginService workFlowFeginService;

    @Resource
    private InternalPurchaseMapper internalPurchaseMapper;

    @Resource
    private IDictionaryService dictionaryService;

    @Resource
    private IApprovalService approvalService;

    @Resource
    private TranspondEmailService transpondEmailService;

    @Resource
    FeginService feginService;

    @Value("${webSit.web}")
    private String webSitUrl;

    /**
     * 保存采购信息
     * @param purchaseOrder
     * @return
     */
    @Transactional
    public Integer saveOrUpdatePurchaseOrder(PurchaseOrderVO purchaseOrder,String token){
        //1.发起工作流
        //获取部门主管
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setAccount(AuthUtils.getUserAccount());
        SysUserEntity user = feginService.queryDeptByLeaderID(userEntity,token).getResult();
        //获取人员信息
        Integer businessId = this.startPurchaseOrdeApproval(user);
        //2.记录本地审批数据
        //生成审批主表信息，日志信息
        ApprovalVO approval = approvalService.initApprovalAndLog(businessId, 57, purchaseOrder.getAskReason(),
                "", -1,"");
        //之后更新/保存
        purchaseOrder.setApprovalId(approval.getApprovalId());

        if( null == purchaseOrder.getPurchaseId() ){
            //生成采购单号
            purchaseOrder.setPurchaseNo(purchaseOrder.getPurchaseNo().replace("...",this.getPurchaseOrdeMaxNumByDate()));
            //保存主表信息
            internalPurchaseMapper.savePurchaseOrder(purchaseOrder);
            Integer purchaseOrdeId=  purchaseOrder.getPurchaseId();

            PurchaseOrderVO purchaseOrderVO = this.getPurchaseOrdeInfoById(purchaseOrdeId);
        }else {
            //1.备份主表信息
            //2.备份从表信息
            internalPurchaseMapper.backUpPurchaseOrder(purchaseOrder);
            internalPurchaseMapper.updatePurchaseOrder(purchaseOrder);
        }
        //保存从表信息
        internalPurchaseMapper.savePurchaseOrderProduct(purchaseOrder.getPurchaseOrderProducts(),purchaseOrder.getPurchaseId());
        //保存抄送人
        transpondEmailService.insertTranspondEmailInfoByUser(purchaseOrder.getApprovalId(),purchaseOrder.getForwardUsers());
        if(AuthUtils.getUserAccount().equals(user.getAccount())){
            //跳过第一步审批
            this.approvePurchaseOrderInfo(purchaseOrder,token,true);
        }else {
            //发送审批邮件
            //发送邮件
            approvalService.updateNextApproverByApprovalId(user.getUserId(),approval.getApprovalId());
//            String titel = "【系统通知】采购信息 - 流程单审批通知";
//            String msg = "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
//                    "<div><p style='text-indent: 2em'>您好，您有一张新的采购信息审批需要处理：</p></div>"+
//                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请人："+ AuthUtils.getUserName() +" / "+ AuthUtils.getUserAccount()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请原因："+ (StringUtils.isEmpty(purchaseOrder.getAskReason()) ? "无":purchaseOrder.getAskReason())+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请时间："+ DateUtils.getCurrentTime() +"</p></div>"+
//                    "<div><p style='text-indent: 2em'>采购名称："+purchaseOrder.getPurchaseTopic()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>采购单号："+purchaseOrder.getPurchaseNo()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>付款期次：共"+purchaseOrder.getPaymentPlanPeriod()+"期</p></div>"+
//                    "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
//                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
//                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),null,titel,msg,token));
            //调用通知接口生成待办通知
            Integer userId = AuthUtils.getUserId();
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(approval.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                    userId,0,57,user.getUserId(),token));
       }
        return purchaseOrder.getPurchaseId();
    }

    /**
     * 获取当日最大采购单号
     * @return
     */
    public String getPurchaseOrdeMaxNumByDate(){
        Integer num = internalPurchaseMapper.getPurchaseOrdeMaxNumByDate();
        if(num<10)
            return "0"+num;
        else
            return num.toString();
    }

    /**
     * 更具项目ID获取所有采购信息
     */
    public List<PurchaseOrderVO> queryPurchaseOrdersByProjectId(Integer projectId){
        return internalPurchaseMapper.queryPurchaseOrdersByProjectId(projectId);
    }

    /**
     * 更具机会ID查询采购信息
     */
    public List<PurchaseOrderVO> queryPurchaseOrdersByOpId(Integer opId){
        return internalPurchaseMapper.queryPurchaseOrdersByOpId(opId);
    }

    /**
     * 更具采购单ID获取采购信息
     * @param purchaseOrdeId
     * @return
     */
    public PurchaseOrderVO getPurchaseOrdeInfoById(Integer purchaseOrdeId){
        PurchaseOrderVO purchaseOrde = internalPurchaseMapper.getPurchaseOrdeInfoById(purchaseOrdeId);
        purchaseOrde.setForwardUsers(transpondEmailService.queryTranspondByApprovalId(purchaseOrde.getApproval().getApprovalId()));
        return purchaseOrde;
    }

    /**
     * 采购信息驳回审批
     * @param purchaseOrder
     * @return
     */
    @Transactional
    public Boolean rejectionPurchaseOrderInfo(PurchaseOrderVO purchaseOrder, String token){
        //获取工作流ID
        ApprovalVO approval = approvalService.queryApprovalByAppID(purchaseOrder.getApprovalId());

        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
//        ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
        //删除流程实例
        workFlowFeginService.deleteInstance(activitiVO);
        //驳回
//        workFlowFeginService.rejectedByBusinessId(activitiVO);
        SysUserEntity user = null;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser;
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(),token).getResult();
        //当第一步为商务时，驳回至起点
//        if( "商务审批".equals(processNodeNameAndCode.getResult().getName()) ){
            user = askUser;
            workState = 1;
            titel= "【系统通知】采购信息 - 流程单审批驳回通知";
            msg = "<div><p >" + "尊敬的" + askUser.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您提交的采购信息审批已被驳回：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批人："+askUser.getLoginName()+" / "+askUser.getAccount()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批意见："+(StringUtils.isEmpty(purchaseOrder.getAppReason()) ? "无":purchaseOrder.getAppReason())+"</p></div>"+
                    "<div><p style='text-indent: 2em'>审批时间："+ DateUtils.getCurrentTime() +"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购名称："+purchaseOrder.getPurchaseTopic()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购单号："+purchaseOrder.getPurchaseNo()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 项目信息管理 - 项目信息 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=projectmanage&me=projectmanageInfo'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
            approvalService.approvalRejection(null,purchaseOrder.getApprovalId());
            todoUser = 0;
//        }else {
//            //获取上一人
//            if("财务审批".equals(processNodeNameAndCode.getResult().getName())){
//                user = dictionaryService.queryMenuUserIdsByCode("commercialSpecialist").get(0);
//            }else if("售后审批".equals(processNodeNameAndCode.getResult().getName())){
//                user = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
//            }else if("总经理审批".equals(processNodeNameAndCode.getResult().getName())){
//                user = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
//            }else if("董事长审批".equals(processNodeNameAndCode.getResult().getName())){
//                user = dictionaryService.queryMenuUserIdsByCode("president").get(0);
//            }
//            workState = 0;
//            titel = "【系统通知】采购信息审批待处理通知";
//            msg =  initPurchaseOrdeEmailData(user.getLoginName(),"您有一张采购审批已被上级驳回需处理"
//                    ,approval.getApprovalCode(), askUser.getLoginName(),purchaseOrder.getPurchaseTopic(),purchaseOrder.getPurchaseNo(),
//                    purchaseOrder.getPaymentPlanPeriod());
//            todoUser = user.getUserId();
//            approvalService.updateNextApproverByApprovalId(user.getUserId(),purchaseOrder.getApprovalId());
//        }
        //记录日志
        approvalService.insertApprovalLog(approval.getApprovalId(),"驳回",
                "",purchaseOrder.getAppReason());
        SysUserEntity finalUser = user;
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(),null,titel,msg,token));
        Integer userId = AuthUtils.getUserId();
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(purchaseOrder.getApprovalId(),  approval.getCreateDataTime(),
                userId,workState,57,todoUser,token));
        return true;
    }

    /**
     * 采购信息通过审批
     * @param purchaseOrder
     * @return
     */
    @Transactional
    public Boolean approvePurchaseOrderInfo(PurchaseOrderVO purchaseOrder,String token,Boolean auto){
        //获取工作流ID
        ApprovalVO approval = approvalService.queryApprovalByAppID(purchaseOrder.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
        SysUserEntity user = null;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser;
        String ccUser = null;
        //整体通过
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(),token).getResult();
        //记录审批日志
        if(auto){
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "系统判定跳过",purchaseOrder.getAppReason());
        }else {
            //记录日志
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "",purchaseOrder.getAppReason());
        }
        if( "售后审批".equals(processNodeNameAndCode.getResult().getName()) ){
            //审批通过
            workFlowFeginService.approvalProcessByBusinessId(activitiVO);
            user=askUser;
            workState = 1;
            todoUser = 0;
            titel= "【系统通知】采购信息 - 流程单审批通过通知";
            msg =  "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您提交的采购信息审批已通过：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购名称："+purchaseOrder.getPurchaseTopic()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>采购单号："+purchaseOrder.getPurchaseNo()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 项目信息管理 - 项目信息 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=projectmanage&me=projectmanageInfo'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
            ccUser = queryContractCC();
            approvalService.approved(null,purchaseOrder.getApprovalId());
            String transpondEmails = transpondEmailService.selectTranspondEmailStr(purchaseOrder.getApprovalId());
            if(!transpondEmails.isEmpty()){
                ccUser = ccUser + "," + transpondEmails;
            }
            SysUserEntity finalUser = user;
            String finalCcUser = ccUser;
            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(), finalCcUser,titel,msg,token));
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(purchaseOrder.getApprovalId(),  approval.getCreateDataTime(),
                    approval.getCreator(),workState,57,todoUser,token));
        }else {
            if("部门主管审批".equals(processNodeNameAndCode.getResult().getName())) {
                user = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
                activitiVO.getCustomParams().put("afterSales", user.getAccount());
            }
            //审批通过（使用动态入参传入下一审批人）
            workFlowFeginService.approvalProcessCustomUserByBusinessId(activitiVO);
            //获取下一节点
            ResponseAPI<ActivitiVO> nextProcessNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
            if(nextProcessNodeNameAndCode.getResult().getAssignee().equals(processNodeNameAndCode.getResult().getAssignee())){
                this.approvePurchaseOrderInfo(purchaseOrder,token,true);
            }else {
                workState = 0;
                //交由下一审批人处理
                todoUser = user.getUserId();
                approvalService.updateNextApproverByApprovalId(user.getUserId(),purchaseOrder.getApprovalId());
                CompletableFuture.runAsync(() -> NoticUtils.pushNotic(purchaseOrder.getApprovalId(),  approval.getCreateDataTime(),
                        approval.getCreator(),workState,57,todoUser,token));
            }
        }
        return true;
    }

    /**
     * 通过申请表主键查询现有数据
     * @param approvalId
     * @return
     */
    public PurchaseOrderVO queryPurchaseOrderByApprovalId(Integer approvalId){
        PurchaseOrderVO purchaseOrde = internalPurchaseMapper.queryPurchaseOrderByApprovalId(approvalId);
        purchaseOrde.setForwardUsers(transpondEmailService.queryTranspondByApprovalId(approvalId));
        return purchaseOrde;
    }

    /**
     * 通过申请表主键查询历史
     * @param approvalId
     * @return
     */
    public PurchaseOrderVO queryPurchaseOrderHistoryByApprovalId(Integer approvalId){
        PurchaseOrderVO purchaseOrder = internalPurchaseMapper.queryPurchaseOrderHistoryByApprovalId(approvalId);
        if(purchaseOrder == null){
            purchaseOrder = internalPurchaseMapper.queryPurchaseOrderByApprovalId(approvalId);
        }
        purchaseOrder.setForwardUsers(transpondEmailService.queryTranspondByApprovalId(approvalId));
        return purchaseOrder;
    }
    @Override
    public List<PurchaseOrderVO> getPurOrdeInfoById(int purchaseOrdeId) {
        return internalPurchaseMapper.getPurOrdeInfoById( purchaseOrdeId);
    }

    /**
     * 开启审批流程
     * @param
     * @param user
     * @return
     */
    private Integer startPurchaseOrdeApproval(SysUserEntity user){
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setProcessName("内部采购");
        activitiVO.setProcessCode("internalPurchase");
        activitiVO.setNextNodeParams("deptLeader");
        activitiVO.setNextNodeAssignee(user.getAccount());
        ResponseAPI<ActivitiVO> responseAPI = workFlowFeginService.startMaxVersionProcessByDesignCodeCustomParams(activitiVO);
        return responseAPI.getResult().getBusinessId();
    }

    /**
     * 生成邮件内推
     * @param userName 邮件通知人
     * @param msgTopic 邮件主题
     * @param approvalCode 事项编号
     * @param askeUserName 申请人
     * @param purchaseOrdeTopic 采购名称
     * @param purchaseOrdeNo 采购单号
     * @param bmpPeriod 付款期次
     * @return
     */
    private String initPurchaseOrdeEmailData(String userName,String msgTopic,String approvalCode,String askeUserName,
                                         String purchaseOrdeTopic, String purchaseOrdeNo,Integer bmpPeriod){
        String msg =  "<div><p >" + "尊敬的" + userName + "：</p></div>" +
                "<div><p style='text-indent: 2em'>您好，"+msgTopic +"：</p></div>"+
                "<div><p style='text-indent: 2em'>事项编号："+approvalCode+"</p></div>"+
                "<div><p style='text-indent: 2em'>申请人："+askeUserName+"</p></div>"+
                "<div><p style='text-indent: 2em'>采购名称："+purchaseOrdeTopic+"</p></div>"+
                "<div><p style='text-indent: 2em'>合同单号："+purchaseOrdeNo+"</p></div>"+
                "<div><p style='text-indent: 2em'>付款期次：共"+bmpPeriod+"期</p></div>";
        if(msgTopic.contains("处理")){
            msg += "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
        }else {
            msg += "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
        }
        return msg;
    }

    /**
     * 获取采购抄送人
     * @return
     */
    private String queryContractCC(){
        //获取抄送人
        List<SysUserEntity> userIds = dictionaryService.queryCcUserIdsByCode("purchaseCC");
        StringBuilder emailList = new StringBuilder();
        for (int i = 0; i < userIds.size(); i++) {
            if (userIds.size()-1 == i){
                emailList.append(userIds.get(i).getEmail());
            }else {
                emailList.append(userIds.get(i).getEmail());
                emailList.append(",");
            }
        }
        return emailList.toString();
    }

    /**
     * 分页查询
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<PurchaseOrderVO> queryPurchaseOrdesByPage(IPage page, PurchaseOrderVO entity, String token){
        List<SysUserEntity> userList = this.queryUserList(AuthUtils.getUserId(),"internalPurchase", token);
        IPage<PurchaseOrderVO> iPage = internalPurchaseMapper.queryPurchaseOrdesByPage(page, entity,userList);
        List<PurchaseOrderVO> list = iPage.getRecords();
        if(!list.isEmpty()){
            BigDecimal totlePricePage = new BigDecimal(0);
            for (PurchaseOrderVO pVo: list) {
                if(pVo.getTotlePrice()!= null){
                    totlePricePage = totlePricePage.add( new BigDecimal(pVo.getTotlePrice()));
                }
            }
            list.get(0).setTotlePricePage(String.valueOf(totlePricePage));
            iPage.setRecords(list);
        }
        return new PageUtil(iPage);
    }

    /**
     * 分页查询待办信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<PurchaseOrderVO> queryApprovalPurByPage(IPage page, PurchaseOrderVO entity){
        //获取工作流待办
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<List<ActivitiVO>> workFlowVoResponseAPI = workFlowFeginService.getTasksByAuthorization(activitiVO);
        List<ActivitiVO> activitiVOS = workFlowVoResponseAPI.getResult();
        if( activitiVOS == null || activitiVOS.size() == 0 ){
            return new PageUtil(new PageDTO());
        }else{
            return new   PageUtil(internalPurchaseMapper.queryApprovalPurByPage(page, entity,activitiVOS));
        }
    }

    /**
     * 分页查询已办信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<PurchaseOrderVO> queryApprovalPurDoneByPage(IPage page, PurchaseOrderVO entity){
        IPage<PurchaseOrderVO> iPage = internalPurchaseMapper.queryApprovalPurDoneByPage(page, entity);
        return new PageUtil(iPage);
    }


    /**
     * 分页查询申请记录信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<PurchaseOrderVO> queryApprovalPurRecordByPage(IPage page, PurchaseOrderVO entity,String token){
        List<SysUserEntity> userList = this.queryUserList(AuthUtils.getUserId(),"approvalRecord", token);
        IPage<PurchaseOrderVO> iPage = internalPurchaseMapper.queryApprovalPurRecordByPage(page, entity,userList);
        return new PageUtil(iPage);
    }

    /**
     * 一指禅系统产品列表导出
     *
     * @param response
     */
    public void exportPurchaseOrdes(HttpServletResponse response, PurchaseOrderVO entit, String token) throws Exception{
        List<SysUserEntity> userList = this.queryUserList(AuthUtils.getUserId(),"internalPurchase", token);
        List<PurchaseOrderVO> purchaseOrdes = internalPurchaseMapper.queryPurchaseOrdes(entit,userList);
        List<String> codes = new ArrayList<>();
        codes.add("purchaseType");
        Map<String, List<DictionaryLookupItemVO>> stringListMap = dictionaryService.queryDictionaryLookupInfo(null, codes);
        for (int i = 0; i < purchaseOrdes.size(); i++) {
            PurchaseOrderVO purchaseOrder = purchaseOrdes.get(i);
            //采购类型
            for(DictionaryLookupItemVO dictionaryLookupItemVO : stringListMap.get("purchaseType") ){
                if(dictionaryLookupItemVO.getItemCode().equals(purchaseOrder.getPurchaseType()+"")){
                    purchaseOrder.setPurchaseTypeStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }

            if(Integer.valueOf(0).equals(purchaseOrder.getPurchaseCategories())){
                purchaseOrder.setPurchaseCategoriesStr("机会采购");
                purchaseOrder.setProjectManageTheme(purchaseOrder.getOpportunityTheme());
            }else {
                purchaseOrder.setPurchaseCategoriesStr("项目采购");
            }


            if(0 == purchaseOrder.getApproval().getApprovalStatus()){
                purchaseOrder.setApprovalStr("审批中");
            }else if(1 == purchaseOrder.getApproval().getApprovalStatus()){
                purchaseOrder.setApprovalStr("已通过");
            }else if(2 == purchaseOrder.getApproval().getApprovalStatus()){
                purchaseOrder.setApprovalStr("已驳回");
            }else if(3 == purchaseOrder.getApproval().getApprovalStatus()){
                purchaseOrder.setApprovalStr("已撤回");
            }else if(5 == purchaseOrder.getApproval().getApprovalStatus()){
                purchaseOrder.setApprovalStr("撤回中");
            }
            purchaseOrder.setPurchaseDateStr(String.format("%tY-%<tm-%<td",purchaseOrder.getPurchaseDate()));
        }

        //获取yml模板位置
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        String path = "application.yml";
        factoryBean.setResources(new ClassPathResource(path));
        Properties properties = factoryBean.getObject();
        String contractTemplatePath = String.valueOf(properties.get("report.purchaseTemplate"));

        //依据根目录获取模板位置
        TemplateExportParams params = new TemplateExportParams(contractTemplatePath);
        Map<String, Object> map = new HashMap<>();
        map.put("purchaseInfos",purchaseOrdes);
        ReportUtils.exportExcel(params,map,"采购列表",response);
    }

    public List<SysUserEntity> queryUserList(Integer userId,String authCode, String token) {
        List<SysUserEntity> userList = new ArrayList<>();
        List<SysUserEntity> authUserIList = dictionaryService.queryAuthUserIdsByCode(authCode);
        boolean result = false;
        for (SysUserEntity user:authUserIList) {
            if (Objects.equals(user.getUserId(), userId)) {
                result = true;
            }
        }
        if (result) {
            userList = feginService.getUserIgnoreFlag(token).getResult();
        } else {
            SysUserEntity user = feginService.searchUserInfoByIds(userId,token).getResult();
            if (user.getIsLeader() == 1) {
                userList = feginService.recursiveQueryAllUserByLeaderId(userId, token).getResult();
            }
            userList.add(user);
        }
        return userList;
    }

    public Boolean deletePurchaseOrderById(Integer purchaseOrdeId){
        return internalPurchaseMapper.deletePurchaseOrderById(purchaseOrdeId);
    }


    @Override
    public List<PurchaseOrderVO> selectAllProjectByPur(){
        return internalPurchaseMapper.selectAllProjectByPur();
    }
}
